package cn.lg.soar.boot.fc.controller;

import cn.lg.soar.boot.client.entity.Applicant;
import cn.lg.soar.boot.client.entity.ClientUser;
import cn.lg.soar.boot.client.entity.vo.ClientUserVo;
import cn.lg.soar.boot.client.service.ApplicantService;
import cn.lg.soar.boot.client.service.ClientUserService;
import cn.lg.soar.boot.fc.entity.FormCollect;
import cn.lg.soar.boot.fc.entity.FormItem;
import cn.lg.soar.boot.fc.entity.Process;
import cn.lg.soar.boot.fc.entity.ProcessExamine;
import cn.lg.soar.boot.fc.entity.vo.FormResultEntityVo;
import cn.lg.soar.boot.fc.entity.vo.FormResultVo;
import cn.lg.soar.boot.fc.service.FormCollectService;
import cn.lg.soar.boot.fc.service.ProcessExamineService;
import cn.lg.soar.common.data.msg.I18n;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.core.annotations.IdempotentByParam;
import cn.lg.soar.core.annotations.constraints.group.Create;
import cn.lg.soar.core.annotations.constraints.group.Update;
import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.database.query.SqueryWapper;
import cn.lg.soar.mvc.enums.ControllerConst;
import cn.lg.soar.database.query.QueryParams;
import cn.lg.soar.mvc.annotations.Log;
import cn.lg.soar.system.auth.entity.Org;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.lg.soar.database.base.controller.BaseController;
import cn.lg.soar.boot.fc.entity.FormResult;
import cn.lg.soar.boot.fc.service.FormResultService;

/**
 * 表单项目提交结果表
 * @author ZhuanZ（无密码）
 * @since 2025-01-17
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Api(tags = "表单项目提交结果表")
@Validated
@RestController
@RequestMapping("fc/formResult")
public class FormResultController extends BaseController<FormResult, FormResultService> {
    @Resource
    private ProcessExamineService processExamineService;
    @Resource
    private FormCollectService formCollectService;
    @Resource
    private ClientUserService clientUserService;
    @Resource
    private ApplicantService applicantService;

    @Override
    protected Serializable getId(FormResult entity) {
        return entity.getId();
    }

    @Log(value = "新增表单项目提交结果表", data = "#p0", dataId = "#$r.data")
    @IdempotentByParam("#p0")
    @ApiOperation(value = ControllerConst.CREATE_NAME)
    @RequestMapping(path = "create", method = RequestMethod.POST)
    public HttpResult<Serializable> create(@RequestBody @Validated(Create.class) FormResult data) {
        return super.createResult(data);
    }

    @Log(value = "修改表单项目提交结果表", data = "#p0", dataId = "#p0.id")
    @ApiOperation(value = ControllerConst.UPDATE_NAME)
    @RequestMapping(path = "update", method = RequestMethod.POST)
    public HttpResult<Void> update(@RequestBody @Validated(Update.class) FormResult data) {
        return super.updateResult(data);
    }

    @Log(value = "删除表单项目提交结果表", data = "#p0")
    @ApiOperation(value = ControllerConst.REMOVE_NAME, notes = "根据 id 删除")
    @RequestMapping(path = "remove", method = RequestMethod.POST)
    public HttpResult<Void> remove(@RequestBody List<Long> ids) {
        return super.removeResult(ids);
    }

    @ApiOperation(value = ControllerConst.DETAIL_NAME, notes = "根据 ID 获取一条数据")
    @RequestMapping(path = "detail", method = RequestMethod.GET)
    public HttpResult<FormResult> detail(@RequestParam Long id) {
        return super.detailResult(id);
    }

    @ApiOperation(value = "表单详情", notes = "根据 ID 获取一条数据")
    @RequestMapping(path = "formDetail", method = RequestMethod.GET)
    public HttpResult<List<FormResultVo>> formDetail(@RequestParam Long id) {
        List formResultList = new ArrayList<>();
        FormResult formResult = super.service.getById(id);
        JSONArray jsonArray = JSONArray.parseArray(formResult.getFormContentConfig());
        for (int i = 0; i < jsonArray.size(); i++) {
            FormResultVo formResultVo = new FormResultVo();
            formResultVo.setFormItemLabel((String) jsonArray.getJSONObject(i).get("value"));
            formResultVo.setFormItemValue(JSONObject.parseObject(formResult.getProcessData()).getString((String) jsonArray.getJSONObject(i).get("formItemField")));
            formResultList.add(formResultVo);
        }
        return HttpResult.data(formResultList);
    }

    @ApiOperation(value = ControllerConst.QUERY_NAME, notes = "多功能查询（分页、列表、统计）")
    @RequestMapping(path = "query", method = RequestMethod.GET)
    public HttpResult<PageResult<FormResultEntityVo>> query(PageQuery pageQuery, QueryParams params){
        SqueryWapper squeryWapper = new SqueryWapper<>(ClientUser.class);
        QueryWrapper<ClientUser> wrapper = Wrappers.query();
        List<String> clientUserF = new ArrayList<>();
        clientUserF.add("userName-like~"+params.getF());
        squeryWapper.setWhere(params.getF(), wrapper);
        List<ClientUser> list1 = clientUserService.list(wrapper);

        params.setF(new ArrayList<>());
        StringBuilder userIds = new StringBuilder();
        if(!list1.isEmpty()) {
            for (ClientUser clientUser : list1) {
                userIds.append("~").append(clientUser.getId());
            }
            params.getF().add("submitUserId-in"+userIds);
        }
        params.setFields(new ArrayList<>());
        PageResult<FormResultEntityVo> pageResult = new PageResult<>();
        List<FormResultEntityVo> list = new ArrayList<>();
        List<FormResult> recordQuery = super.queryResult(pageQuery, params).getData().getList();
        for (FormResult record : recordQuery) {
            FormResultEntityVo vo = new FormResultEntityVo();
            BeanUtils.copyProperties(record, vo);
            ClientUser user = clientUserService.getById(record.getSubmitUserId());
            if(user != null) {
                vo.setUserName(user.getUserName());
            }
            FormCollect formCollect = formCollectService.getById(record.getCollectId());
            if(formCollect != null){
                vo.setCollectName(formCollect.getCollectName());
            }
            list.add(vo);
        }
        pageResult.setList(list);
        return HttpResult.data(pageResult);
    }

    @Log(value = "导出表单项目提交结果表")
    @ApiOperation(value = ControllerConst.EXPORT_NAME)
    @RequestMapping(path = "export", method = RequestMethod.GET)
    public void exports(String filename, QueryParams params, HttpServletResponse resp){
        super.exportExcel(filename, params, resp);
    }

    @Log(value = "导入表单项目提交结果表")
    @ApiOperation(value = ControllerConst.IMPORT_NAME)
    @RequestMapping(path = "import", method = RequestMethod.POST)
    public HttpResult<Void> imports(HttpServletRequest req){
        return super.importExcel(req);
    }

    @ApiOperation(value = ControllerConst.DETAIL_NAME, notes = "根据 ID 获取表单项目提交结果数据")
    @GetMapping("/formResultDetail")
    public HttpResult<List<FormResultVo>> formResultDetail(@RequestParam Long id) {
        List formResultList = new ArrayList<>();
        ProcessExamine processExamine = processExamineService.getById(id);
        FormResult formResult = super.service.getById(processExamine.getCustomFormId());
        JSONArray jsonArray = JSONArray.parseArray(formResult.getFormContentConfig());
        for (int i = 0; i < jsonArray.size(); i++) {
            FormResultVo formResultVo = new FormResultVo();
            formResultVo.setFormItemLabel((String) jsonArray.getJSONObject(i).get("value"));
            formResultVo.setFormItemValue(JSONObject.parseObject(formResult.getProcessData()).getString((String) jsonArray.getJSONObject(i).get("formItemField")));
            formResultList.add(formResultVo);
        }
        return HttpResult.data(formResultList);
    }

    @ApiOperation(value = ControllerConst.DETAIL_NAME, notes = "根据 ID 获取表单项目提交结果数据")
    @GetMapping("/userFormResultDetail")
    public HttpResult<List<FormResultVo>> userFormResultDetail(@RequestParam Long id) {
        List formResultList = new ArrayList<>();
//        ClientUser user = clientUserService.getById(id);
        Applicant applicant = applicantService.getById(id);
        FormResult formResult = super.service.getById(applicant.getFormResultId());
        JSONArray jsonArray = JSONArray.parseArray(formResult.getFormContentConfig());
        for (int i = 0; i < jsonArray.size(); i++) {
            FormResultVo formResultVo = new FormResultVo();
            formResultVo.setFormItemLabel((String) jsonArray.getJSONObject(i).get("value"));
            formResultVo.setFormItemValue(JSONObject.parseObject(formResult.getProcessData()).getString((String) jsonArray.getJSONObject(i).get("formItemField")));
            formResultList.add(formResultVo);
        }
        return HttpResult.data(formResultList);
    }

}